<template>
  <div class="ds-manage-page">
    <el-card>
      <div class="header-bar">
        <span class="title">数据源管理</span>
        <el-button type="primary" size="small" @click="openEditDialog()">新增数据源</el-button>
      </div>
      <el-table :data="dsList" border>
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column prop="type" label="类型" min-width="90">
          <template #default="scope">
            <el-tag :type="dsTypeTag(scope.row.type)">
              {{ getTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="desc" label="描述" min-width="160"/>
        <el-table-column prop="conn" label="连接信息/文件" min-width="210"/>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteDS(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑/新增数据源弹窗 -->
    <el-dialog v-model="dialogVisible" :title="editDS.id ? '编辑数据源' : '新增数据源'" width="420px">
      <el-form :model="editDS" :rules="formRules" ref="formRef" label-width="82px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editDS.name" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="editDS.type" placeholder="选择类型">
            <el-option v-for="item in dsTypes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="editDS.desc" />
        </el-form-item>
        <el-form-item v-if="editDS.type==='api'" label="API地址" prop="conn">
          <el-input v-model="editDS.conn" placeholder="如：https://api.xxx.com/data"/>
        </el-form-item>
        <el-form-item v-else-if="editDS.type==='db'" label="数据库连接" prop="conn">
          <el-input v-model="editDS.conn" placeholder="如：mysql://user:pass@host:port/db"/>
        </el-form-item>
        <el-form-item v-else-if="editDS.type==='excel'" label="文件名" prop="conn">
          <el-input v-model="editDS.conn" placeholder="如：/data/demo.xlsx"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="saveDS">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 数据源类型
const dsTypes = [
  { value: 'api', label: 'API接口' },
  { value: 'db', label: '数据库' },
  { value: 'excel', label: 'Excel文件' }
]
function getTypeName(type) {
  const found = dsTypes.find(t => t.value === type)
  return found ? found.label : type
}
function dsTypeTag(type) {
  if (type === 'api') return 'success'
  if (type === 'db') return 'warning'
  if (type === 'excel') return 'info'
  return ''
}

// 默认模拟数据源
const defaultDS = [
  { id: 1, name: '演示API', type: 'api', desc: '生产环境REST接口', conn: 'https://api.demo.com/data' },
  { id: 2, name: '本地数据库', type: 'db', desc: 'MySQL测试数据库', conn: 'mysql://user:pwd@127.0.0.1:3306/test' },
  { id: 3, name: '年度销量Excel', type: 'excel', desc: '导入的年度销售数据', conn: '/data/sale2023.xlsx' }
]

const dsList = ref([])
function initDS() {
  const local = JSON.parse(localStorage.getItem('dsList') || 'null')
  if (!local) {
    localStorage.setItem('dsList', JSON.stringify(defaultDS))
    dsList.value = defaultDS
  } else {
    dsList.value = local
  }
}

onMounted(initDS)

// 编辑/新增数据源弹窗
const dialogVisible = ref(false)
const editDS = reactive({
  id: null,
  name: '',
  type: '',
  desc: '',
  conn: ''
})
const formRef = ref()
const formRules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  desc: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  conn: [{ required: true, message: '请输入连接信息', trigger: 'blur' }]
}

function openEditDialog(row = null) {
  if (row) {
    editDS.id = row.id
    editDS.name = row.name
    editDS.type = row.type
    editDS.desc = row.desc
    editDS.conn = row.conn
  } else {
    editDS.id = null
    editDS.name = ''
    editDS.type = ''
    editDS.desc = ''
    editDS.conn = ''
  }
  dialogVisible.value = true
}

function saveDS() {
  formRef.value.validate((valid) => {
    if (!valid) return
    let dsArr = JSON.parse(localStorage.getItem('dsList') || '[]')
    if (editDS.id) {
      // 编辑
      dsArr = dsArr.map(ds => ds.id === editDS.id ? { ...editDS } : ds)
    } else {
      // 新增
      const maxId = dsArr.reduce((max, ds) => Math.max(max, ds.id), 0)
      dsArr.unshift({ ...editDS, id: maxId + 1 })
    }
    localStorage.setItem('dsList', JSON.stringify(dsArr))
    dsList.value = dsArr
    ElMessage.success('保存成功！')
    dialogVisible.value = false
  })
}

function deleteDS(row) {
  const dsArr = dsList.value.filter(ds => ds.id !== row.id)
  localStorage.setItem('dsList', JSON.stringify(dsArr))
  dsList.value = dsArr
  ElMessage.success('已删除！')
}
</script>

<style scoped>
.ds-manage-page {
  padding: 24px;
  background: #f7f8fa;
  min-height: 95vh;
}
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.title {
  font-size: 20px;
  font-weight: 600;
}
</style>
